package org.axeidls.filter;

import java.lang.reflect.Method;

import org.axe.annotation.common.Nullable;
import org.axe.annotation.ioc.Value;
import org.axe.annotation.mvc.Request;
import org.axe.annotation.mvc.UnFuckOff;
import org.axe.bean.mvc.Handler;
import org.axe.bean.mvc.Header;
import org.axe.bean.mvc.HttpRequestPack;
import org.axe.bean.mvc.HttpResponsePack;
import org.axe.bean.mvc.Param;
import org.axe.exception.RestException;
import org.axe.interface_implement.mvc.HeaderFilter;
import org.axe.util.StringUtil;
import org.mindrot.jbcrypt.BCrypt;

@UnFuckOff
public class AuthFilter extends HeaderFilter{

	@Nullable
	@Value("${axe.nvgt.my-app-name}")
	private String myAppName;

	@Value("${server.readonly}")
	private Boolean readonly;
	
	@Nullable
	@Value("${server.access-token-encrypted}")
	private String accessTokenEncrypted;
	
	@Override
	public Header[] headers() {
		return new Header[] {
			new Header("accessToken")
		};
	}
	
	@Override
	public boolean doFilter(Header[] headers, HttpRequestPack request, HttpResponsePack response, Param param,Handler handler) {
		//限制可访问接口列表
		if(readonly) {
			if(!handler.getRequestMethod().equals("GET")) {
				throw new RestException(RestException.SC_FORBIDDEN,"只读模式，禁止访问此接口");
			}
		}
		
		if(StringUtil.isEmpty(accessTokenEncrypted)) {
			return true;
		}
		
		String token = null;
		if(headers[0] != null) {
			token = headers[0].getValue();
		}
		
		if(StringUtil.isEmpty(token)) {
			throw new RestException(RestException.SC_UNAUTHORIZED,"凭证缺失，禁止访问");
		}
		
		boolean check = BCrypt.checkpw(token, accessTokenEncrypted);
        if(!check) {
			throw new RestException(RestException.SC_UNAUTHORIZED,"凭证无效，禁止访问");
        }
		
		return true;
	}
	
	@Override
	public boolean mapping(String requestMethod, String mappingPath, Request request, Method actionMethod) {
		if(StringUtil.isNotEmpty(myAppName)) {
			if(mappingPath.startsWith("/"+myAppName+"/axe")) {
				return false;
			}
		}else {
			if(mappingPath.startsWith("/axe")) {
				return false;
			}
		}
		return true;
	}

}
